#include <iostream>
#include <cerrno>
#include <string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Thread.hpp"
#include "InetAddr.hpp"
void Usage(const std::string& process)
{
    std::cout << "Usage: " << process << "server_ip server_port" << std::endl;
}

class ThreadData
{
public:
    ThreadData(int sock, struct sockaddr_in &server): _sockfd(sock), _serveraddr(server)
    {}
public:
    int _sockfd;
    InetAddr _serveraddr;

};

void RecverRoutine(ThreadData& td)
{
    while(true)
    {
        char buffer[4096];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        
        std::cout << "Waiting for server response..." << std::endl;
        ssize_t n = recvfrom(td._sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &len);
        std::cout << "Received " << n << " bytes from server" << std::endl;
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "get message: " << buffer << std::endl; //方便一会查看效果
            std::cout.flush();
        }
        else 
        {
            std::cerr << "recvfrom failed: " << strerror(errno) << std::endl;
            std::cout.flush();
            break;
        }
    }
}

void SenderRoutine(ThreadData& td)    
{
    while(true)
    {
        std::string inbuffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, inbuffer);
        
        auto server = td._serveraddr.GetAddr();


        // 添加发送调试信息
        ssize_t n = sendto(td._sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server , sizeof(struct sockaddr_in));
        if(n < 0)
            std::cout << "send error" << std::endl;
        else 
            std::cout << "Send " << n << " bytes to server" << std::endl;
        
    }
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //1.创建socket, 就是创建了文件细节
    //
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        std::cerr << "socket error: " << strerror(errno) << std::endl;
        return 2;
    }

    std::cout << "create socket success: " << sock << std::endl;
    //2. client要不要进行bind?  一定要bind的！！ 但是，不需要显示bind，client会在首次发送数据的时候会自动进行bind
    //为什么？ server端的端口号，一定是众所周知的，不可改变的，client 需要 port， bind随机端口，
    //为什么？ client会非常多，
    //client 需要bind, 但是不需要显示bind，让本地os自动随机bind，选择随机端口号
    //2.1 填充一下server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    std::string test_msg = "Connection test";
    ssize_t test = sendto(sock, test_msg.c_str(), test_msg.size(), 0, 
                         (struct sockaddr*)&server, sizeof(struct sockaddr_in));
    if(test < 0)
    {
        std::cerr << "Failed to connect to server: " << strerror(errno) << std::endl;
        close(sock);
        return 3;
    }
    else
    {
        std::cout << "Successfully connected to server at " << serverip << ":" << serverport << std::endl;
    }


    ThreadData td(sock, server);

    Thread<ThreadData> recver("recver", RecverRoutine, td);
    Thread<ThreadData> sender("sender", SenderRoutine, td);

    recver.Start();
    sender.Start();
   

    recver.Join();
    sender.Join();

    close(sock);
    return 0;
}